<?php

namespace register\model;

require_once("./login/model/UserCredentials.php");
require_once("./login/model/UserList.php");
require_once("./login/model/UserName.php");
require_once("./login/model/Password.php");
require_once("./common/model/ErMsg.php");

class RegisterModel {
	
	private static $registerUser = "LoginModel::registerUser";
	
	private $observer;
	private $userList;
	
	public function __construct($observer) {
		$this->observer = $observer;
		$this->userList = new \login\model\UserList();
	}
	
	public function createUser($username, $password) {
		try {
			$user = \login\model\UserCredentials::create($username, $password);
			return $user;
		}
		catch (\Exception $e) {
			\Debug::log("Register user failed", false, $e->getMessage());
			throw $e;
		}
	}
	
	public function saveUser($user) {
		$this->userList->update($user);
	}
	
	public function userAlreadyExists($username) {
		$this->userList->findUserName($username);
	}
	
	public function createUsername($str) {
		try {
			$username = new \login\model\UserName($str);
			return $username;
		}
		catch (\Exception $e) {
			\Debug::log("Register username failed", false, $e->getMessage());
			throw $e;
		}
	}
	
	public function createPassword($str) {
		try {
			$password = \login\model\Password::fromCleartext($str);
			return $password;
		}
		catch (\Exception $e) {
			\Debug::log("Register password failed", false, $e->getMessage());
			throw $e;
		}
	}
	
	public function isPasswordsSame($passwordOne, $passwordTwo) {
		if ($passwordOne != $passwordTwo) {
			throw new \Exception(\common\model\ErMsg::$PasswordDoNotMatch);
		}
	}
	
	public function showUserWasRegisteredMessage() {
		$_SESSION[self::$registerUser]->showMessage = true;
	}
	
	public function setSessionUsername($username) {
		$_SESSION[self::$registerUser]->username = $username; 
	}

}
